package com.example.leetdemo.finash;

import java.util.ArrayList;
import java.util.List;

public class Solution117 {

    public Node connect(Node root) {
        List<Node> arr = new ArrayList<>();
        arr.add(null);
        while (arr.size() > 0) {
            List<Node> temp = new ArrayList<>();
            for (int i = 0; i < arr.size(); i++) {
                Node node = arr.get(i), next = i == arr.size()- 1 ? null : arr.get(i + 1);
                if (node.left != null) {
                    temp.add(node.left);
                }
                if (node.right != null) {
                    temp.add(node.right);
                }
                node.next = next;
            }
            arr = temp;
        }
        return root;
    }



    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
